package com.sinsz.pay.open;

import com.fcibook.quick.http.QuickHttp;
import com.sinsz.pay.exception.PayException;
import com.sinsz.pay.properties.PayProperties;
import com.sinsz.pay.util.PayUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.sinsz.pay.properties.support.WeChatPlatform.PUBLIC;

/**
 * 微信授权实现
 * @author chenjianbo
 */
@Service
public class WeChatOAService {

    private final PayProperties properties;

    private static final Logger logger = LoggerFactory.getLogger(WeChatOAService.class);

    private static final String WX_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize";

    private static final String WX_OPENID = "https://api.weixin.qq.com/sns/oauth2/access_token";

    @Autowired
    public WeChatOAService(PayProperties properties) {
        this.properties = properties;
    }

    /**
     * 验证平台
     */
    private void validate() {
        if (!PUBLIC.equals(properties.getWxpay().getPlatform())) {
            throw new PayException("当前不是微信公众号平台.");
        }
    }

    String fetchCode(final String api) {
        validate();
        return "redirect:" + WX_CODE + "?appid=" + properties.getWxpay().getAppid() +
                "&redirect_uri=" + PayUtils.redirect(properties.getHttp(), api, true) +
                "&response_type=code" +
                "&scope=snsapi_base" +
                "#wechat_redirect";
    }

    String fetchOpenid(HttpServletRequest request) {
        validate();
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            throw new PayException("扫码获取用户授权失败,请重试.");
        }
        Map<String, String> param = new HashMap<>(4);
        param.put("appid", properties.getWxpay().getAppid());
        param.put("secret", properties.getWxpay().getSecret());
        param.put("code", code);
        param.put("grant_type", "authorization_code");
        String result = new QuickHttp().url(WX_OPENID).get().addParames(param).text();
        logger.info("执行了微信授权获取openid请求, {}", result);
        Map<String, String> map = Json.fromJsonAsMap(String.class, result);
        String defKey = "openid";
        if (!map.containsKey(defKey)) {
            throw new PayException("扫码获取用户授权失败,请重试.");
        }
        String openid = map.getOrDefault(defKey, "");
        if (StringUtils.isEmpty(properties.getWxpay().getWeChatPublicNumberRedirect())) {
            throw new PayException("重定向地址不能为空.");
        }
        return "redirect:" + PayUtils.redirect(properties.getHttp(), properties.getWxpay().getWeChatPublicNumberRedirect(), false) + "?openid=" + openid;
    }

}
